package app

import (
	"github.com/fuxiaohei/hxgo"
	"path"
	"os"
)

// view vars
var (
	View *hxgo.View
)

// init view struct
func initView() {
	d := path.Join(Root, "views")
	View = hxgo.NewView(d)
	// load view cache setting
	View.IsCache = Cfg.Bool("ViewCache")
	Log.Info("[" + Name + "]", "load view")
	// write view error page
	initViewErrorPage(d)
}

// init default error page
func initViewErrorPage(d string) {
	// get error page from config
	page := Cfg.StringOr("ViewErrorPage", "error.html")
	_, e := View.Create(page, nil)
	if os.IsNotExist(e) {
		// if error template is none, create one
		f := path.Join(d, page)
		fs, e2 := os.Create(f)
		if e2 != nil {
			panic(e2)
		}
		defer fs.Close()
		fs.Write([]byte(errorPageHtml))
	}
}

// error template html string
var errorPageHtml = `<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Error</title>
    <style type="text/css">
        * {
            margin: 0;padding: 0; font-family: "Consolas", "Microsoft YaHei", "Courier New", Arial, sans-serif;
            font-size: 13px;line-height: 24px;list-style: none;color: #444;
        }
        #top{
            background-color: #ffedf6;padding:12px 24px;border-bottom: 1px solid #CCC;
        }
        #s{
            padding: 12px 24px;border-bottom: 1px solid #DDD;
        }
        #i{
            padding: 12px 24px;color: #999;font-size: 12px;
        }
        h1{
            font-size: 24px;line-height: 40px;color: #f33618;margin-bottom: 8px;
        }
        h3{
            font-size: 16px;line-height: 30px;
        }
        #r li{
            list-style: disc inside;
        }
        #r strong{
            display: inline-block;width: 112px;
        }
        #i strong{
            display: inline-block;width: 60px;
        }
    </style>
</head>
<body>
<div id="top">
    <h1>{{.error.Err}}</h1>
    <ul id="r">
        <li><strong>RequestURL</strong>{{.request.RequestURI}}</li>
        <li><strong>RequestMethod</strong>{{.request.Method}}</li>
        <li><strong>RemoteAddr</strong>{{.request.RemoteAddr}}</li>
        <li><strong>UserAgent</strong>{{.request.UserAgent}}</li>
    </ul>
</div>
{{if .isDev}}
<div id="s">
    <h3>Stack</h3>
    <pre>{{.stack}}</pre>
</div>
{{end}}
<div id="i">
    <p><strong>{{.app}}</strong>{{.appVersion}}</p>
    <p><strong>GoLang</strong>{{.goVersion}}</p>
    <p><strong>HxGo</strong>{{.hxgoVersion}}</p>
</div>
</body>
</html>`

